<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ name: 'goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert title="添加商品信息" type="info" show-icon :closable="false" center></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="casacderProps" @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(value, i) in item.attr_vals" :key="i" :label="value" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action图片上传地址 -->
            <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headerObj" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce" />
            <!-- 添加按钮 -->
            <el-button type="primary" class="add-btn" @click="addGoods()">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt="" class="preview-img" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_price: null,
        goods_weight: null,
        goods_number: null,
        // 商品所属分类数组
        goods_cat: [],
        //图片的数组
        pics: [],
        //商品内容
        goods_introduce: "",
        //商品参数数据
        attrs: [],
      },
      addFormRules: {
        goods_name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          { type: "number", message: "价格必须为数字值" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
          { type: "number", message: "重量必须为数字值" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
          { type: "number", message: "数量必须为数字值" },
        ],
      },
      cateList: [],
      //   级联选择器配置
      casacderProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover",
      },
      //动态参数数据
      manyData: [],
      //静态属性数据
      onlyData: [],
      //上传地址
      uploadURL: "http://www.tangxiaoyang.vip:8888/api/v2/upload",
      // 文件上传的请求头
      headerObj: {
        Authorization: JSON.parse(sessionStorage.getItem("userInfo")).token,
      },
      previewVisible: false,
      previewPath: "",
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.cateList = res.data;
    },
    //监听级联选择器
    handleChange() {
      if (this.addForm.goods_cat.length != 3) {
        this.addForm.goods_cat = [];
      }
    },
    //tabs切换前触发
    beforeTabLeave(activeName, oldActiveName) {
      if (this.addForm.goods_cat.length != 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    //tabs点击时触发
    async tabClicked() {
      //判断动态还是静态
      if (this.activeIndex == "1") {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: "many" },
        });
        if (res.meta.status != 200) {
          return this.$message.error("获取动态参数失败");
        }
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        });
        this.manyData = res.data;
      } else if (this.activeIndex == "2") {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: "only" },
        });
        if (res.meta.status != 200) {
          return this.$message.error("获取静态失败");
        }
        this.onlyData = res.data;
      }
    },
    //图片预览
    handlePreview(file) {
      this.previewPath = file.url;
      this.previewVisible = true;
    },
    //图片移除
    handleRemove(file) {
      //1.获取要删除图片的临时路径
      const filePath = file.response.data.tmp_path;
      //2.从pic数组中，找到该图片的索引位置
      const i = this.addForm.pics.findIndex((item) => {
        item.pic == filePath;
      });
      //3.从pics数组移除
      this.addForm.pics.splice(i, 1);
    },
    //图片会上传成功
    handleSuccess(response) {
      return this.addForm.pics.push({ pic: response.data.tmp_path });
    },
    //添加商品
    addGoods() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        //准备请求前的数据
        //1.处理商品分类的数组换成字符串
        //深拷贝lodash工具
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        //2.处理商品动态参数
        this.manyData.forEach((item) => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          });
        });
        //处理静态属性
        this.onlyData.forEach((item) => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          });
        });
        //发请求
        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status != 201) {
          return this.$message.error("添加商品失败");
        }
        this.$message.success("添加商品成功");
        this.$router.push("/goods");
      });
    },
  },
  computed: {
    cateId() {
      return this.addForm.goods_cat.length == 3 ? this.addForm.goods_cat[2] : null;
    },
  },
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin-right: 10px;
}
.preview-img {
  width: 100%;
}
.add-btn {
  margin-top: 15px;
}
</style>
